package com.alex.dao;

import com.alex.pojo.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository("userDao")
public class UserDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    public User get(int id) {
        String sql = "select * from user where id=" + id;
        BeanPropertyRowMapper<User> userBeanPropertyRowMapper = new BeanPropertyRowMapper<>(User.class);
        User user = jdbcTemplate.queryForObject(sql, userBeanPropertyRowMapper);
        return user;
    }

    public User get02(int id) {
        String sql = "select * from user where id=?";
        BeanPropertyRowMapper<User> userBeanPropertyRowMapper = new BeanPropertyRowMapper<>(User.class);
        User user = jdbcTemplate.queryForObject(sql, userBeanPropertyRowMapper, id);
        return user;
    }

    public boolean add(User user) {
        String sql = "insert into user(username, password) VALUES (?, ?)";
        BeanPropertyRowMapper<User> userBeanPropertyRowMapper = new BeanPropertyRowMapper<>(User.class);
        int result = jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
        return result==1;
    }

    public boolean update(User user) {
        String sql = "update user set username=?, password=? where id=?";
        BeanPropertyRowMapper<User> userBeanPropertyRowMapper = new BeanPropertyRowMapper<>(User.class);
        int result = jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getId());
        return result==1;
    }

    public boolean delete(int id) {
        String sql = "delete from user where id=?";
        BeanPropertyRowMapper<User> userBeanPropertyRowMapper = new BeanPropertyRowMapper<>(User.class);
        int result = jdbcTemplate.update(sql, id);
        return result==1;
    }
}
